#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "positionmanager.h"
#include "config.h"
#include <iostream>
#include <QInputDialog>
#include <QSettings>
#include <QTranslator>
#include <QDebug>
#include <QDateTime>
#include <QMessageBox>

MainWindow* MainWindow::instance = nullptr;
extern QTranslator translator;
extern Config config;


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QIcon windowIcon(":/logo.png");
    setWindowIcon(windowIcon);

    qApp->setStyleSheet("QMainWindow { background-color: #f1f5ff; }"
                        "QPushButton {"
                        "background-color: #a0a0a0; "
                        "border-style: solid; "
                        "border-width: 1px; "
                        "border-radius: 4px; "
                        "border-color: #202020; "
                        "color: #23c96e; "
                        "padding: 5px;"
                        "}"
                        "QPushButton:hover {"
                        "background-color: #e0e0e0;"
                        "}"
                        "QPushButton:pressed {"
                        "background-color: #e0e0e0;"
                        "}"
                        "QLabel {"
                        "color: #202020;"
                        "}"
                        "QLineEdit {"
                        "background-color: #c0c0c0; "
                        "color: #2030e0;"
                        "border-style: solid; "
                        "border-width: 1px; "
                        "border-color: #202020;"
                        "}"
                        "QWidget {"
                        "background-color: #f1f5ff;"
                        "}"
                        "QComboBox {"
                        "color: #b0b0b0;"
                        "}"
                        "QComboBox QAbstractItemView {"
                        "color: #b0b0b0;"
                        "}"
                        );

    ui->languageSelector->blockSignals(true);
    ui->languageSelector->addItem("English", "en");
    ui->languageSelector->addItem("中文", "zh");
    ui->languageSelector->blockSignals(false);

    // Select current language
    QString currentLang = config.get("lang");
    qDebug() << "Current lang: " << currentLang;
    int index = ui->languageSelector->findData(currentLang);
    if (index != -1) {
        ui->languageSelector->setCurrentIndex(index);
    }

    instance = this;
}

MainWindow::~MainWindow()
{
    if (routeTrainDialog != NULL) {
        delete routeTrainDialog;
    }

    if (ui != NULL) {
        delete ui;
        ui = NULL;
    }

    instance = NULL;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(hHook) UnhookWindowsHookEx(hHook);
    QMainWindow::closeEvent(event);
}




// 点击 初始化
void MainWindow::on_btn_init_clicked()
{
    if (0 == positionManager.init()) {
        if (!positionManager.loadPos()) return;
        displayPositions();

        // 加载热键
        loadHotKey();

        // 监听全系统键盘时间
        if(hHook) UnhookWindowsHookEx(hHook);
        hHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, GetModuleHandle(NULL), 0);

        ui->lineEdit_searchPosStorage->setDisabled(false);
        ui->btn_teleportRolePos->setDisabled(false);
        ui->btn_saveCurrentPos->setDisabled(false);
        ui->btn_trackRolePos->setDisabled(false);
        ui->btn_reset_drakePos->setDisabled(false);
        ui->btn_pause_resume_drake->setDisabled(false);

        ui->btn_set_teleportRolePos_hotKey->setDisabled(false);
        ui->btn_set_trackRolePos_hotKey->setDisabled(false);
        ui->btn_set_frameRate30_hotKey->setDisabled(false);
        ui->btn_set_frameRate60_hotKey->setDisabled(false);
        ui->btn_set_frameRate90_hotKey->setDisabled(false);
        ui->btn_set_frameRate120_hotKey->setDisabled(false);

        ui->btn_showRouteTrainDialog->setDisabled(false);

        ui->btn_init->setDisabled(true);
        ui->btn_init->setText("已经初始化完毕 (游戏重启, 该软件也需要重启)");
    } else {
        ui->btn_init->setText("初始化失败, 点击重新初始化");
    }
}





// 展示坐标存档列表
void MainWindow::displayPositions(const QString& searchText)
{
    // 清除之前的 存档 候选项
    for (QLabel* label : positionLabels) {
        delete label;
    }
    positionLabels.clear();

    for (QPushButton* button : deleteButtons) {
        delete button;
    }
    deleteButtons.clear();

    // 删除之前的 QScrollArea QWidget
    QLayoutItem* item;
    while ((item = ui->verticalLayout_positions->takeAt(0)) != nullptr) {
        delete item->widget();
        delete item;
    }


    // 初始化 QScrollArea
    QScrollArea* scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);

    // 初始化 QWidget QVBoxLayout
    QWidget* scrollContent = new QWidget(scrollArea);
    QVBoxLayout* scrollLayout = new QVBoxLayout(scrollContent);
    scrollLayout->setSpacing(0);
    scrollLayout->setContentsMargins(5, 0, 5, 0);

    // 循环遍历存档
    const QList<QJsonObject>& positions = positionManager.getPositions();
    int listCount = 0;
    for (int i=0; i<positions.length(); ++i) {
        const QJsonObject& position = positions[i];
        const QString& positionName = position["name"].toString();
        const bool systemPosition = position["systemPosition"].toBool();

        // 过滤搜索
        if (!searchText.isEmpty() && !positionName.contains(searchText, Qt::CaseInsensitive)) {
            continue;
        }

        // 初始化一个存档的 QWidget
        QWidget* positionWidget = new QWidget(this);
        if (listCount % 2 == 0) {
            QPalette pal = QPalette();
            pal.setColor(QPalette::Window, QColor::fromRgbF(240, 240, 240, 0.1f));
            positionWidget->setStyleSheet("QWidget {"
                                          "background-color: #e0e0e0;"
                                          "}"
                                          );
            positionWidget->setPalette(pal);
        }

        // 初始化一个存档的 QHBoxLayout
        QHBoxLayout* positionLayout = new QHBoxLayout(positionWidget);
        positionLayout->setSpacing(0);
        positionLayout->setContentsMargins(0, 0, 0, 0);

        // 初始化一个存档的 删除按钮
        QPushButton* deleteButton = NULL;
        if (!systemPosition) {
            deleteButton = new QPushButton("🗑", positionWidget);
            deleteButton->setFixedSize(30, 30);
            deleteButton->setCursor(Qt::PointingHandCursor);
            if (listCount % 2 == 0) {
                QPalette pal = QPalette();
                pal.setColor(QPalette::Window, QColor::fromRgbF(0, 0, 0, 0.1f));
                deleteButton->setStyleSheet("QWidget:hover {"
                                              "background-color: #4A4A4A;"
                                              "}"
                                              );
                deleteButton->setPalette(pal);
            } else {
                QPalette pal = QPalette();
                pal.setColor(QPalette::Window, QColor::fromRgbF(0, 0, 0, 0.1f));
                deleteButton->setStyleSheet("QWidget:hover {"
                                            "background-color: #505050;"
                                            "}"
                                            );
                deleteButton->setPalette(pal);
            }
            positionLayout->addWidget(deleteButton);
            deleteButtons.append(deleteButton);
        }

        // 初始化一个存档的 排序往上按钮
        QPushButton* sortUpButton = NULL;
        if (!systemPosition && i > 0) {
            sortUpButton = new QPushButton("↑", positionWidget);
            sortUpButton->setFixedSize(30, 30);
            sortUpButton->setCursor(Qt::PointingHandCursor);
            if (listCount % 2 == 0) {
                QPalette pal = QPalette();
                pal.setColor(QPalette::Window, QColor::fromRgbF(0, 0, 0, 0.1f));
                sortUpButton->setStyleSheet("QWidget:hover {"
                                              "background-color: #4A4A4A;"
                                              "}"
                                              );
                sortUpButton->setPalette(pal);
            } else {
                QPalette pal = QPalette();
                pal.setColor(QPalette::Window, QColor::fromRgbF(0, 0, 0, 0.1f));
                sortUpButton->setStyleSheet("QWidget:hover {"
                                            "background-color: #505050;"
                                            "}"
                                            );
                sortUpButton->setPalette(pal);
            }
            positionLayout->addWidget(sortUpButton);
            deleteButtons.append(sortUpButton);
        }

        // 初始化一个存档的 名称标签控件
        QLabel* nameLabel = new QLabel(positionName, positionWidget);
        nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        nameLabel->setFont(QFont("Arial", 12));
        nameLabel->setContentsMargins(10, 0, 0, 0);
        positionLayout->addWidget(nameLabel);
        positionLabels.append(nameLabel);

        // 初始化一个存档的 复制到当前坐标的按钮
        QPushButton* interactButton = new QPushButton("➜", positionWidget);
        interactButton->setFixedSize(30, 30);
        interactButton->setCursor(Qt::PointingHandCursor);
        if (i % 2 == 0) {
            QPalette pal = QPalette();
            pal.setColor(QPalette::Window, QColor::fromRgbF(0, 0, 0, 0.1f));
            interactButton->setStyleSheet("QWidget:hover {"
                                        "background-color: #4A4A4A;"
                                        "}"
                                        );
            interactButton->setPalette(pal);
        } else {
            QPalette pal = QPalette();
            pal.setColor(QPalette::Window, QColor::fromRgbF(0, 0, 0, 0.1f));
            interactButton->setStyleSheet("QWidget:hover {"
                                        "background-color: #505050;"
                                        "}"
                                        );
            interactButton->setPalette(pal);
        }
        positionLayout->addWidget(interactButton);


        // 删除按钮事件绑定
        if (deleteButton != NULL) {
            connect(deleteButton, &QPushButton::clicked, [this, i]() {
                positionManager.deletePosition(i);
                displayPositions();
            });
        }

        // ↑按钮事件绑定
        if (sortUpButton != NULL) {
            connect(sortUpButton, &QPushButton::clicked, [this, i]() {
                positionManager.sortUpPosition(i);
                displayPositions();
            });
        }

        // →按钮事件绑定
        connect(interactButton, &QPushButton::clicked, [this, i, positionName]() {
            positionManager.usePosition(i);
            display_track();
            ui->lineEdit_currentPosName->setText(positionName);
        });


        scrollLayout->addWidget(positionWidget);
        listCount++;
    }

    // Définit le widget de contenu dans la zone de scroll
    scrollContent->setLayout(scrollLayout);
    scrollArea->setWidget(scrollContent);

    // Ajoute la zone de scroll au layout vertical des positions
    ui->verticalLayout_positions->addWidget(scrollArea);
}

// 搜索坐标存档点
void MainWindow::on_lineEdit_searchPosStorage_textChanged(const QString& searchText)
{
    displayPositions(searchText);
}




// 展示当前坐标
void MainWindow::display_track() {
    ui->label_currentXPosValue->setText(QString::number(positionManager.getX()));
    ui->label_currentYPosValue->setText(QString::number(positionManager.getY()));
    ui->label_currentZPosValue->setText(QString::number(positionManager.getZ()));
}




// 点击 读取当前人物坐标
void MainWindow::on_btn_trackRolePos_clicked()
{
    if (!positionManager.trackRolePosition()) {
        QMessageBox::critical(nullptr, "错误", "读取当然人物坐标失败");
        return;
    }
    display_track();

    QDateTime current_date_time = QDateTime::currentDateTime();
    QString current_date = current_date_time.toString("MM.dd hh:mm:ss");
    ui->lineEdit_currentPosName->setText(current_date + " 人物坐标");
}

// 点击 将人物传送至如下坐标
void MainWindow::on_btn_teleportRolePos_clicked()
{
    positionManager.teleportRole();
}

// 点击 保存当前坐标
void MainWindow::on_btn_saveCurrentPos_clicked()
{
    // 弹出输入框, 输入坐标的存档名称
    bool bOk = false;
    QString sName = QInputDialog::getText(this,
                                         "新建坐标存档",
                                         "请输入存档名称",
                                         QLineEdit::Normal,
                                         "000 - 龙的屁股",
                                         &bOk
                                         );
    if (bOk && !sName.isEmpty()) {
        positionManager.createPosition(sName);
        positionManager.savePositionsToFile("pos.json");
        positionManager.loadPos();
        displayPositions();
        ui->lineEdit_currentPosName->setText(sName);
    }
}


void MainWindow::on_label_drake_linkActivated(const QString &link)
{
    ui->lineEdit_currentPosName->setText("selected");
}

void MainWindow::setPositionName(const QString &name){
    ui->lineEdit_currentPosName->setText(name);
}





// 监听全局键盘消息
LRESULT CALLBACK MainWindow::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == HC_ACTION) {
        switch (wParam) {
        case WM_KEYDOWN:
        case WM_SYSKEYDOWN:
            KBDLLHOOKSTRUCT *pKeyStruct = (KBDLLHOOKSTRUCT*)lParam;
            if (pKeyStruct->vkCode == MainWindow::instance->vkCode_teleportRole) {
                MainWindow::instance->positionManager.teleportRole();
            } else if (pKeyStruct->vkCode == MainWindow::instance->vkCode_trackRolePos) {
                MainWindow::instance->on_btn_trackRolePos_clicked();
            } else if (pKeyStruct->vkCode == MainWindow::instance->vkCode_frameRate30) {
                MainWindow::instance->positionManager.setFps(30);
            } else if (pKeyStruct->vkCode == MainWindow::instance->vkCode_frameRate60) {
                MainWindow::instance->positionManager.setFps(60);
            } else if (pKeyStruct->vkCode == MainWindow::instance->vkCode_frameRate90) {
                MainWindow::instance->positionManager.setFps(90);
            } else if (pKeyStruct->vkCode == MainWindow::instance->vkCode_frameRate120) {
                MainWindow::instance->positionManager.setFps(120);
            }
            break;
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

static QString generateHotKeyDesc(int hotKey) {
    return hotKey >= 0 ? "热键为 " + QString((char)hotKey) : "无热键";
}
static void loadHotKey(
        const QString& hotKeyStoreKey, int& hotKeyMemory,
        QPushButton* setHotKeyBtn, const QString& setHotKeyBtnPrefix) {
    QString configStoreString = config.get(hotKeyStoreKey);
    bool toint_ok = false;
    if (configStoreString != NULL && configStoreString.length() > 0) {
        hotKeyMemory = configStoreString.toInt(&toint_ok);
    }
    if (!toint_ok) {
        hotKeyMemory = -1000;    // 默认值
        config.set(hotKeyStoreKey, "-1000");
    }
    setHotKeyBtn->setText(setHotKeyBtnPrefix + generateHotKeyDesc(hotKeyMemory));
}
// 加载热键
void MainWindow::loadHotKey()
{
    ::loadHotKey("vkCode_trackRolePos", vkCode_trackRolePos, ui->btn_trackRolePos, "读取当前人物坐标, ");
    ::loadHotKey("vkCode_teleportRole", vkCode_teleportRole, ui->btn_teleportRolePos, "将人物传送至如下坐标, ");
    ::loadHotKey("vkCode_frameRate30", vkCode_frameRate30, ui->btn_set_frameRate30_hotKey, "设置切30帧率热键 : ");
    ::loadHotKey("vkCode_frameRate60", vkCode_frameRate60, ui->btn_set_frameRate60_hotKey, "设置切60帧率热键 : ");
    ::loadHotKey("vkCode_frameRate90", vkCode_frameRate90, ui->btn_set_frameRate90_hotKey, "设置切90帧率热键 : ");
    ::loadHotKey("vkCode_frameRate120", vkCode_frameRate120, ui->btn_set_frameRate120_hotKey, "设置切120帧率热键 : ");
}
bool setHotKeyByQInputDialog(
        const QString& hotKeyStoreKey, int& hotKeyMemory,
        QPushButton* setHotKeyBtn, const QString& setHotKeyBtnPrefix,
        QWidget* parent,
        const QString& hotKeyName)
{
    bool toint_ok;
    int initValue = config.get(hotKeyStoreKey).toInt(&toint_ok, 10);
    QString initString = initValue>=0 ? QString((char)initValue) : "";

    bool ok;
    QString text = QInputDialog::getText(parent, "设置 "+hotKeyName+" 热键",
                                         "热键 (只支持一个符号, 清除代表没有) :", QLineEdit::Normal,
                                         initString, &ok);
    if (ok) {
        if (!text.isEmpty()) {
            hotKeyMemory = VkKeyScanEx(text[0].toLatin1(), GetKeyboardLayout(0)) & 0xFF;
        } else {
            hotKeyMemory = -1000;
        }
        config.set(hotKeyStoreKey, QString::number(hotKeyMemory));
        config.save("config.ini");
        setHotKeyBtn->setText(setHotKeyBtnPrefix + generateHotKeyDesc(hotKeyMemory));
    }
    return ok;
}
// 点击 "设置 传送人物坐标 热键"
void MainWindow::on_btn_set_teleportRolePos_hotKey_clicked()
{
    ::setHotKeyByQInputDialog(
                "vkCode_teleportRole", vkCode_teleportRole,
                ui->btn_teleportRolePos, "将人物传送至如下坐标, ",
                this, "将人物传送至如下坐标");
}
// 点击 "设置 读取当前人物坐标 热键"
void MainWindow::on_btn_set_trackRolePos_hotKey_clicked()
{
    ::setHotKeyByQInputDialog(
                "vkCode_trackRolePos", vkCode_trackRolePos,
                ui->btn_trackRolePos, "读取当前人物坐标, ",
                this, "读取当前人物坐标");
}
void MainWindow::on_btn_set_frameRate30_hotKey_clicked() {
    ::setHotKeyByQInputDialog(
                "vkCode_frameRate30", vkCode_frameRate30,
                ui->btn_set_frameRate30_hotKey, "设置切30帧率热键, ",
                this, "设置切30帧率热键");
}
void MainWindow::on_btn_set_frameRate60_hotKey_clicked() {
    ::setHotKeyByQInputDialog(
                "vkCode_frameRate60", vkCode_frameRate60,
                ui->btn_set_frameRate60_hotKey, "设置切60帧率热键, ",
                this, "设置切60帧率热键");
}
void MainWindow::on_btn_set_frameRate90_hotKey_clicked() {
    ::setHotKeyByQInputDialog(
                "vkCode_frameRate90", vkCode_frameRate90,
                ui->btn_set_frameRate90_hotKey, "设置切90帧率热键, ",
                this, "设置切90帧率热键");
}
void MainWindow::on_btn_set_frameRate120_hotKey_clicked() {
    ::setHotKeyByQInputDialog(
                "vkCode_frameRate120", vkCode_frameRate120,
                ui->btn_set_frameRate120_hotKey, "设置切120帧率热键, ",
                this, "设置切120帧率热键");
}





// 初始化龙
void MainWindow::on_btn_reset_drakePos_clicked()
{
    int speed = positionManager.resetDrake();
}
// 暂停/开始 龙的运动
void MainWindow::on_btn_pause_resume_drake_clicked()
{
    if ("暂停龙" == ui->btn_pause_resume_drake->text()) {
        positionManager.pauseDrake();
        ui->btn_pause_resume_drake->setText("让龙飞");
    } else {
        int speed = positionManager.resetSpeedDrake();
        ui->btn_pause_resume_drake->setText("暂停龙");
    }
}




void MainWindow::on_languageSelector_currentIndexChanged(int index)
{
    QString newLang = ui->languageSelector->itemData(index).toString();

    // Change la langue dans le fichier de config
    config.set("lang", newLang);
    config.save("config.ini");

    // Recharge la traduction
    QLocale locale;
    if (newLang == "en") {
        locale = QLocale(QLocale::English, QLocale::UnitedKingdom);
    } else if (newLang == "fr") {
        locale = QLocale(QLocale::French, QLocale::France);
    } else if (newLang == "zh") {
        locale = QLocale(QLocale::Chinese, QLocale::China);
    }

    const QString baseName = "OnlyUP_Trainer_" + locale.name();
    if (translator.load(":/i18n/" + baseName)) {
        qApp->installTranslator(&translator);
        ui->retranslateUi(this);  // retranslate the user interface
    } else {
        qDebug() << "Failed to load translation:" << baseName;
    }
}




void MainWindow::on_btn_showRouteTrainDialog_clicked()
{
    if (routeTrainDialog != NULL) {
        delete routeTrainDialog;
        routeTrainDialog = NULL;
    }
    routeTrainDialog = new RouteTrainDialog(&positionManager, this);
    routeTrainDialog->show();

    ui->btn_showRouteTrainDialog->setDisabled(true);
    ui->btn_showRouteTrainDialog->setText("速通训练中");
}

void MainWindow::routeTrainDialogClosed()
{
    if (ui != NULL) {
        ui->btn_showRouteTrainDialog->setText("开始速通训练");
        ui->btn_showRouteTrainDialog->setDisabled(false);
    }
}
